import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {FetchService} from '../../../core/net/fetch.service';
import {NzMessageService} from 'ng-zorro-antd';
import {Router} from "@angular/router";

export interface Data {
  id: number;
  name: string;
  year: string;
  manager: string;
  telephone: string;
  type: string;
  districtId: number;
  address: string;
}


@Component({
  selector: 'app-project-files-management',
  templateUrl: './project-files.component.html',
  styleUrls: ['./project-files.component.scss']
})
export class ProjectFilesComponent implements OnInit {
  searchForm: FormGroup;
  isAllDisplayDataChecked = false;
  isIndeterminate = false;
  listOfDisplayData: Data[] = [];
  listOfAllData: Data[] = [];
  mapOfCheckedId: { [key: string]: boolean } = {};
  numberOfChecked = 0;
  delDisable = true;

  form: FormGroup;
  modalTitle: string = '';
  modalShow: boolean = false;
  nzBodyStyle: any = {
    padding: '16px 20px 0'
  };
  allChecked = false;
  indeterminate = false;

  projectChartOption = {
    color: ['#3398DB'],
    tooltip: {
      trigger: 'axis',
      axisPointer: {            // 坐标轴指示器，坐标轴触发有效
        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      splitLine: {
        show: true
      },
      data: []
    },
    yAxis: {
      type: 'value',
      splitLine: {
        show: true
      },
      splitArea: {show: true}
    },
    series: [
      {
        name: '数量',
        type: 'bar',
        barWidth: '60%',
        data: []
      }
    ]
  };
  projectChartMergeOption;

  pieChartOption = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)'
    },
    legend: {
      bottom: 0,
      data: ['信息化工程', '涉外工程']
    },
    series: [
      {
        name: '访问来源',
        type: 'pie',
        radius: '55%',
        center: ['50%', '50%'],
        data: [
          {value: 335, name: '信息化工程'},
          {value: 310, name: '涉外工程'},
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };
  pieChartMergeOption;

  constructor(private fb: FormBuilder,
              private fetchService: FetchService,
              private router: Router,
              private message: NzMessageService) {
    this.searchForm = this.fb.group({
      name: [''],
      year: [''],
      type: ['']
    });
  }

  ngOnInit(): void {
    this.queryInfo();
    this.getChartData();
  }

  queryInfo(): void {
    const param = {
      name: this.searchForm.value.name,
      year: this.searchForm.value.year,
      type: this.searchForm.value.type
    };
    this.fetchService.post<any>('archives/wrsProjectInfo/list', param).subscribe(res => {
      this.listOfAllData = res.list;
    });
  }

  getChartData(): void {
    // {"data":{"typeList":[{"type":"1","num":2}],"yearList":[{"year":"2015","num":1},{"year":"2019","num":1}]}}
    this.fetchService.post<any>('archives/wrsProjectInfo/statistic', {}).subscribe(res => {
      this.projectChartMergeOption = {
        xAxis: {
          data: res.yearList.map(item => item.year + '年')
        },
        series: [
          {
            data: res.yearList.map(item => item.num)
          }
        ]
      };
    });
  }

  currentPageDataChange($event: Data[]): void {
    this.listOfDisplayData = $event;
    this.refreshStatus();
  }

  refreshStatus(): void {
    this.delDisable = Object.keys(this.mapOfCheckedId).length > 0 ? false : true;
    this.isAllDisplayDataChecked = this.listOfDisplayData
      .every(item => this.mapOfCheckedId[item.id]);
    this.isIndeterminate =
      this.listOfDisplayData.some(item => this.mapOfCheckedId[item.id]) &&
      !this.isAllDisplayDataChecked;
    this.numberOfChecked = this.listOfAllData.filter(item => this.mapOfCheckedId[item.id]).length;
  }

  checkAll(value: boolean): void {
    this.listOfDisplayData.forEach(item => (this.mapOfCheckedId[item.id] = value));
    this.refreshStatus();
  }

  openEditModal(item?): void {
    this.router.navigate(['/project-files/project-files-detail'], {queryParams: {id: item.id}});
  }


  onDelete(id) {
    this.fetchService.post('archives/wrsProjectInfo/delete', {ids: [id]}).subscribe(resp => {
      this.message.info('删除成功');
      this.queryInfo();
    });
  }

  onDeleteAll() {
    const ids = Object.keys(this.mapOfCheckedId);
    this.fetchService.post('archives/wrsProjectInfo/delete', {ids: ids}).subscribe(resp => {
      this.message.info('删除成功');
      this.queryInfo();
    });
  }

  onConfirm() {
    if (!this.form.valid) {
      this.message.warning('信息填写有误');
      return;
    }
    const data = this.form.value;
    if (data.id) {
      this.fetchService.post('archives/wrsProjectInfo/edit', data).subscribe(res => {
        this.modalShow = false;
        this.queryInfo();
      });
    } else {
      this.fetchService.post('archives/wrsProjectInfo/add', data).subscribe(res => {
        this.modalShow = false;
        this.queryInfo();
      });
    }
  }

  onAdd(): void {
    this.router.navigate(['/project-files/project-files-detail'], {queryParams: {id: ''}});
  }

  onCancel() {
    this.modalShow = false;
  }


}
